//
//  YHYAddViewController.m
//  Home
//
//  Created by 杨泓晔 on 16/4/27.
//  Copyright © 2016年 LanJue. All rights reserved.
//

#import "YHYActivityIntroductionViewController.h"
#import "YHYCompanyAddPictureCell.h"
#import "WSShopInfoNextView.h"
#import "DCPaymentView.h"
#import "WSCustomPickerView.h"
#import "AppDelegate.h"
#import "YHYSelectViewController.h"
#import "TZTestCell.h"
//#import "YHYSeaPictureViewController.h"
#import "TZImagePickerController.h"
//#import "UIView+Five.h"
#import "UIView+Layout.h"
#import "YHYDesignRequireTableViewCell.h"
#import "YHYStyleTableViewCell.h"
#import "YHYButtonTableViewCell.h"
#import "SeaPictureViewController.h"

#import "YHYPictureCollectionViewCell.h"
#import "YHYActivityPictureTableViewCell.h"
#import "AppDelegate.h"
@interface YHYActivityIntroductionViewController ()<UITableViewDataSource,UITableViewDelegate,WSCustomPickerViewDelegate,UITableViewDelegate,UITableViewDataSource,YHYSelectViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate,YHYButtonTableViewdelegate,YHYCompanyAddPicturedelegate,UITextViewDelegate,YHYActivitydelegate>{
    NSInteger index;
    CGFloat _itemWH;
    CGFloat _margin;
    CGFloat _fH;
    NSMutableArray *_selectedAssets;
    
    NSInteger a;
    NSIndexPath *indexP;
    UITapGestureRecognizer *recognizer;
    
    NSIndexPath *indexComP;//点击cell
    UIView *commentsView;
    UITextView *commentText;
}
@property (nonatomic,strong)UITableView *myTableView;
//@property (nonatomic,strong)NSArray *array;
//@property (nonatomic,strong)NSArray *arrTwo;
@property (nonatomic,strong)NSString *name;
@property (nonatomic,strong)WSCustomPickerView *customPicker;
@property (nonatomic,strong)NSString *styleRequire;

@property (nonatomic,strong)YHYSelectViewController *yhy;
//@property (nonatomic,retain)TZTestCell *cell;

@property (nonatomic,strong)AppDelegate *myAppDelegate;
@property (nonatomic,strong)UIView *myBackBigView;
//@property (nonatomic,strong)NSMutableArray *mycollectionVArray;


@property (nonatomic,assign)NSInteger selectArray;
@property (nonatomic,strong)UICollectionViewFlowLayout *layout;
@property (nonatomic,strong)UICollectionView *myCollectionView;
@property (nonatomic,strong)UILabel *numLabel;
@property (nonatomic,strong)UIButton *button;


@property (nonatomic,retain)NSIndexPath *myindexPath;
@property (nonatomic,retain)NSMutableArray *seaArr;
@property (nonatomic,retain)NSIndexPath *tapIndexPath;

@property (nonatomic,strong)UILabel *numL;

@property (nonatomic, assign)BOOL lastIsHidden;
@property (nonatomic, strong)UILabel *animationLabel;

@property (nonatomic,assign)NSInteger numOfContent;
@property (nonatomic, retain)NSString *textStr;//输入内容

@end

@implementation YHYActivityIntroductionViewController

- (void)viewWillAppear:(BOOL)animated {
    
    //    self.navigationController.navigationBarHidden = NO;
    self.title = @"a图片";
    self.tabBarController.tabBar.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"arr" object:nil];
    self.tabBarController.tabBar.hidden=YES;
    
    self.navigationController.navigationBar.translucent = YES;
    
    
    //增加监听，当键盘出现或改变时收出消息
//   [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillShow:)
//                                                 name:UIKeyboardWillShowNotification
//                                               object:nil];
    
    //增加监听，当键退出时收出消息
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillHide:)
//                                                 name:UIKeyboardWillHideNotification
//                                               object:nil];
    [self.myCollectionView reloadData];
}

-(void) viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=NO;
}

- (void)viewDidLoad {
    [self creatView];
    
    self.selectedPhotos = [NSMutableArray array];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(Back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    _margin = 4 * AUTO_HEIGHT;
    _itemWH = (self.view.tz_width - 20 * AUTO_WIDTH-2 * _margin - 7) / 3 - _margin;
    self.layout.itemSize = CGSizeMake(_itemWH, _itemWH  - 1 );
    self.layout.minimumInteritemSpacing = _margin;
    self.layout.minimumLineSpacing = 10  * AUTO_HEIGHT ;
    _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0 * AUTO_WIDTH, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (150 * AUTO_HEIGHT* (0))) collectionViewLayout:self.layout];
    
    
    
    _selectedAssets = [NSMutableArray array];
    self.myindexPath = [NSIndexPath new];
    _seaArr = [NSMutableArray array];
    // self.numLabel = [UILabel new];
    self.tapIndexPath = [NSIndexPath new];
    _myCollectionView.backgroundColor = [UIColor whiteColor];
    
    [_myTableView reloadData];
    // [_myCollectionView reloadData];
    
    
    
    
//    self.animationLabel = [[UILabel alloc] init];
//    self.animationLabel.textAlignment = NSTextAlignmentCenter;
//    self.animationLabel.font = [UIFont systemFontOfSize:15];
//    self.animationLabel.numberOfLines = 1;
//    self.animationLabel.backgroundColor = [UIColor redColor];
//    self.animationLabel.adjustsFontSizeToFitWidth = YES;
//    self.animationLabel.minimumScaleFactor = 0.1;
//    self.animationLabel.layer.borderWidth = 0.45;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)
                                                 name:@"UITextViewTextDidChangeNotification" object:commentText];

}

- (void)creatView{
    
    self.myTableView = [UITableView new];
    
    [self.view addSubview:self.myTableView];
    self.myTableView.rowHeight = 50 * AUTO_HEIGHT;
    
    self.myTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view);
        make.left.mas_equalTo(self.view);
        make.height.mas_equalTo(self.view.frame.size.height + 50 * AUTO_HEIGHT);
        make.width.mas_equalTo(self.view);
        
    }];
    //_myTableView.scrollEnabled = NO;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.backgroundColor = LV;
    [self.myTableView registerClass:[YHYActivityPictureTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[YHYDesignRequireTableViewCell class] forCellReuseIdentifier:@"YHYDesignRequireTableViewCell"];
//    [self.myTableView registerClass:[YHYStyleTableViewCell class] forCellReuseIdentifier:@"YHYStyleTableViewCell"];
    [self.myTableView registerClass:[YHYButtonTableViewCell class] forCellReuseIdentifier:@"YHYButtonTableViewCell"];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ce"];
    [[UITableViewHeaderFooterView appearance] setTintColor:LV];
    //    _myCollectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (150 * AUTO_HEIGHT* (a)));
    
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                               initWithTarget:self action:@selector(longPressGestureRecognized:)];
    
    [self.myTableView addGestureRecognizer:longPress];
    
    
   
    [_myCollectionView reloadData];
    [_myTableView reloadData];
    
}

////长按手势方法
//- (void)longPressGestureRecognized:(id)sender {
//    
//    UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;
//    UIGestureRecognizerState state = longPress.state;
//    
//    CGPoint location = [longPress locationInView:self.myTableView];
//    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:location];
//    
//    static UIView       *snapshot = nil;        ///< A snapshot of the row user is moving.
//    static NSIndexPath  *sourceIndexPath = nil; ///< Initial index path, where gesture begins.
//    
//    switch (state) {
//        case UIGestureRecognizerStateBegan: {
//            if (indexPath) {
//                sourceIndexPath = indexPath;
//                
//                YHYCompanyAddPictureCell *cell = (YHYCompanyAddPictureCell *)[self.myTableView cellForRowAtIndexPath:indexPath];
//                
//                
//                // Take a snapshot of the selected row using helper method.
//                snapshot = [self customSnapshotFromView:cell];
//                
//                // Add the snapshot as subview, centered at cell's center...
//                __block CGPoint center = cell.center;
//                snapshot.center = center;
//                snapshot.alpha = 0.0;
//                [self.myTableView addSubview:snapshot];
//                [UIView animateWithDuration:0.25 animations:^{
//                    
//                    // Offset for gesture location.
//                    center.y = location.y;
//                    snapshot.center = center;
//                    snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);
//                    snapshot.alpha = 0.98;
//                    
//                    // Black out.
//                    cell.backgroundColor = [UIColor blackColor];
//                } completion:nil];
//            }
//            break;
//        }
//        case UIGestureRecognizerStateChanged: {
//            CGPoint center = snapshot.center;
//            center.y = location.y;
//            snapshot.center = center;
//            
//            // Is destination valid and is it different from source?
//            if (indexPath && ![indexPath isEqual:sourceIndexPath]) {
//                
//                // ... update data source.
//                [self.selectedPhotos exchangeObjectAtIndex:indexPath.row withObjectAtIndex:sourceIndexPath.row];
//                
//                // ... move the rows.
//                [self.myTableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];
//                
//                // ... and update source so it is in sync with UI changes.
//                sourceIndexPath = indexPath;
//                
//            }
//            break;
//        }
//        default: {
//            // Clean up.
//            UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:sourceIndexPath];
//            [UIView animateWithDuration:0.25 animations:^{
//                
//                snapshot.center = cell.center;
//                snapshot.transform = CGAffineTransformIdentity;
//                snapshot.alpha = 0.0;
//                
//                // Undo the black-out effect we did.
//                cell.backgroundColor = [UIColor whiteColor];
//                
//            } completion:^(BOOL finished) {
//                
//                [snapshot removeFromSuperview];
//                snapshot = nil;
//                
//            }];
//            sourceIndexPath = nil;
//            break;
//        }
//    }
//    // More coming soon...
//    
//}
- (UIView *)customSnapshotFromView:(UIView *)inputView {
    
    UIView *snapshot = [inputView snapshotViewAfterScreenUpdates:YES];
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    
    return snapshot;
}

#pragma mark - 协议

- (void)buttonAction:(UIButton *)button{
    YHYCompanyAddPictureCell *cell = (YHYCompanyAddPictureCell *)button.superview.superview;
    NSIndexPath *indexPath = [_myTableView indexPathForCell:cell];
    
    if (1001 == button.tag) {
        // 上
        
        
        if (0 == indexPath.row) {
            NSLog(@"到顶了");
        } else {
            [_selectedPhotos exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row - 1];
            
            //            NSArray *arr = @[
            //                             [NSIndexPath indexPathForItem:indexPath.row inSection:0],
            //                             [NSIndexPath indexPathForItem:indexPath.row - 1 inSection:0]];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        }
        
        
    }
    
    if (1002 == button.tag) {
        if (_selectedPhotos.count- 1 == indexPath.row) {
            NSLog(@"到底部");
        }
        else{
            [_selectedPhotos exchangeObjectAtIndex:indexPath.row  withObjectAtIndex:indexPath.row + 1 ];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row+1 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
            [_myTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
        }
    }
    
    if (1000 == button.tag) {
        
        [_selectedPhotos removeObjectAtIndex:indexPath.row];
        [_myTableView reloadData];
    }
    
 }

- (void)showCommentText {
    [self createCommentsView];
    
    [commentText becomeFirstResponder];//再次让textView成为第一响应者（第二次）这次键盘才成功显示
}
- (void)createCommentsView {
    if (!commentsView) {
        
        commentsView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 370 - 40.0, SCREEN_WIDTH, 100.0)];
        commentsView.backgroundColor = [UIColor whiteColor];
        
        commentText = [[UITextView alloc] initWithFrame:CGRectInset(commentsView.bounds, 1, 1)];
        commentText.layer.borderColor   = KH.CGColor;
        commentText.layer.borderWidth   = 2.0;
        commentText.layer.cornerRadius  = 2.0;
        commentText.layer.masksToBounds = YES;
        
        commentText.inputAccessoryView  = commentsView;
        commentText.backgroundColor     = [UIColor clearColor];
        commentText.returnKeyType       = UIReturnKeySend;
        commentText.delegate	    = self;
        commentText.font		= [UIFont systemFontOfSize:16.0];
        [commentsView addSubview:commentText];
    }
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    [delegate.window addSubview:commentsView];//添加到window上或者其他视图也行，只要在视图以外就好了
//    [commentText becomeFirstResponder];//让textView成为第一响应者（第一次）这次键盘并未显示出来，（个人觉得这里主要是将commentsView设置为commentText的inputAccessoryView,然后再给一次焦点就能成功显示）
    
//    UITapGestureRecognizer *ta = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Tap:)];
//    
//    [delegate.window addGestureRecognizer:ta];
}

-(void)Tap:(UITapGestureRecognizer *)taP{
    NSLog(@"dw");
    
 
    UITapGestureRecognizer *longPress = (UITapGestureRecognizer *)taP;
    UIGestureRecognizerState state = longPress.state;
    
        CGPoint location = [longPress locationInView:self.myTableView];
        NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:location];
    
    
  //  NSLog(@"%@",indexPath.row);
//
}




//- (void)keyboardWillShow:(NSNotification *)aNotification
//{
//    //获取键盘的高度
//    /*
//     iphone 6:
//     中文
//     2014-12-31 11:16:23.643 Demo[686:41289] 键盘高度是  258
//     2014-12-31 11:16:23.644 Demo[686:41289] 键盘宽度是  375
//     英文
//     2014-12-31 11:55:21.417 Demo[1102:58972] 键盘高度是  216
//     2014-12-31 11:55:21.417 Demo[1102:58972] 键盘宽度是  375
//     
//     iphone  6 plus：
//     英文：
//     2014-12-31 11:31:14.669 Demo[928:50593] 键盘高度是  226
//     2014-12-31 11:31:14.669 Demo[928:50593] 键盘宽度是  414
//     中文：
//     2015-01-07 09:22:49.438 Demo[622:14908] 键盘高度是  271
//     2015-01-07 09:22:49.439 Demo[622:14908] 键盘宽度是  414
//     
//     iphone 5 :
//     2014-12-31 11:19:36.452 Demo[755:43233] 键盘高度是  216
//     2014-12-31 11:19:36.452 Demo[755:43233] 键盘宽度是  320
//     
//     ipad Air：
//     2014-12-31 11:28:32.178 Demo[851:48085] 键盘高度是  264
//     2014-12-31 11:28:32.178 Demo[851:48085] 键盘宽度是  768
//     
//     ipad2 ：
//     2014-12-31 11:33:57.258 Demo[1014:53043] 键盘高度是  264
//     2014-12-31 11:33:57.258 Demo[1014:53043] 键盘宽度是  768
//     */
//    NSDictionary *userInfo = [aNotification userInfo];
//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [aValue CGRectValue];
//    int height = keyboardRect.size.height;
//    int width = keyboardRect.size.width;
//    NSLog(@"键盘高度是  %d",height);
//    NSLog(@"键盘宽度是  %d",width);
//}

-(void)textFiledEditChanged:(NSNotification *)obj
{
    UITextView *textField = (UITextView *)obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [textField.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
    {
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > 149)
            {
                textField.text = [toBeString substringToIndex:149];
            }
        }
        
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > 149)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:_numOfContent];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:149];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 149)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}
//开始触发键盘
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView

{
    recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapAction:)];
    [self.view addGestureRecognizer:recognizer];
    
    
    if (_selectedPhotos.count != 0) {
        [UIView animateWithDuration:.7f delay:0.f usingSpringWithDamping:.7f initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        } completion:nil];
        
        [UIView animateWithDuration:.3f animations:^{
            self.view.frame = CGRectMake(0, - 150 * AUTO_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
            
        }];
        
    }
    
    
    
    //   [self.view removeGestureRecognizer:recognizer];
    
    
    
    
    return YES;
}


-(void)textViewDidChange:(UITextView *)textView
{
    //    self.textV.text = textView.text;
    //    if (textView.text.length == 0) {
    //        self.uilabel.text = @"一句话介绍自己，和大家打声招呼，写写现在的心情";
    //    }else{
    //        self.uilabel.text = @"";
    //    }
    
    //    self.intA =[self characterCountOfString:self.textV.text];
    //    self.numChiese = [self chineseCountOfString:self.textV.text];
    //    self.numLabel.text = [NSString stringWithFormat:@"%ld/40",(self.numChiese + self.intA)];
    
    
    NSLog(@"dawe");
    
}
- (void)TapAction:(UITapGestureRecognizer *)tap{
    
    [self.view endEditing:YES];
    NSLog(@"hhhhhh=%@",commentText.text);
    
    UITapGestureRecognizer *longPress = (UITapGestureRecognizer *)tap;
    UIGestureRecognizerState state = longPress.state;
    
    CGPoint location = [longPress locationInView:self.myTableView];
    NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:location];
    NSLog(@"%@",indexPath);

    
    
    
    [UIView animateWithDuration:0.20f animations:^{
        
        
        self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        
    }];
    
    
    [commentText resignFirstResponder];
    [self.view removeGestureRecognizer:recognizer];
}



-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        
        [UIView animateWithDuration:0.20f animations:^{
            
            
            self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            
        }];
        
        NSString *temp = [textView.text stringByReplacingCharactersInRange:range
                          withString:text];

       // _textStr = temp;
        
        NSLog(@"uuuu=%@",temp);
        _textStr = temp;
        
        [self heightForContent:temp];
        [_myTableView reloadData];
        return NO;
        
    }
    
    return YES;
    
    
}
//文字是配

- (CGFloat)heightForContent:(NSString *)content
{
    //参数1.设置计算高度按照什么样的size来计算
    //注意: 宽度一定与Label宽度一致，高度尽量大一点
    CGSize size = CGSizeMake(300, 10000);
    //参数2.设置计算类型
    //参数3.设置计算内容按照多大字体计算
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17.0], NSFontAttributeName, nil];
    //注意: 字体大小也要跟Label字体一样
    //参数4.系统备用参数，设置为nil
    CGRect frame = [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    _fH = frame.size.height;
    [_myTableView reloadData];
    return frame.size.height;
}

-(void) tableView: (UITableView *) tableView moveRowAtIndexPath: (NSIndexPath *) oldPath toIndexPath:(NSIndexPath *) newPath

{
    
    [self.myTableView reloadData];
}

//-(BOOL)tableView:(UITableView *) tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    //打开编辑
//    return YES;
//}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    //允许移动
    return YES;
    //return NO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0;
    }
    if (section == 1) {
        return 0;
    }
    if (section == 2) {
        return 0;
    }
    else{
        
        return 8 * AUTO_HEIGHT;
    }
}


//缩微图
- (UIImage *)imageByScalingProportionallyToSize: (CGSize)targetSize {
    
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor < heightFactor)
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor < heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    // this is actually the interesting part:
    UIGraphicsBeginImageContext(targetSize);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    return newImage ;
}
//-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//    //转动特效
//    CATransform3D rotation;
//    rotation = CATransform3DMakeRotation( (90.0*M_PI)/180, 0.0, 0.7, 0.4);
//    rotation.m34 = 1.0/ -600;
//
//    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
//    cell.layer.shadowOffset = CGSizeMake(10, 10);
//    cell.alpha = 0;
//    cell.layer.transform = rotation;
//    cell.layer.anchorPoint = CGPointMake(0, 0.5);
//
//
//    [UIView beginAnimations:@"rotation" context:NULL];
//    [UIView setAnimationDuration:0.8];
//    cell.layer.transform = CATransform3DIdentity;
//    cell.alpha = 1;
//    cell.layer.shadowOffset = CGSizeMake(0, 0);
//    [UIView commitAnimations];
//
//    [UIView animateWithDuration:0.5 animations:^{
//        cell.layer.transform = CATransform3DIdentity;
//        cell.alpha = 1;
//        cell.layer.shadowOffset = CGSizeMake(0, 0);
//    }];
//}
//

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return _selectedPhotos.count;
    }
    
    return 1;
    //    }
    //    return 0;
    
    
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    indexP = indexPath;
    [_myTableView reloadData];
     [self showCommentText];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *str = @"cell";
    
    if (indexPath.section == 0) {
        
        indexComP = indexPath;
        YHYActivityPictureTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:str];
        
        [self imageCompressForSize:[_selectedPhotos objectAtIndex:indexPath.row] targetSize:CGSizeMake(-100, -100)];
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        cell2.delegate = self;
        //        cell2.myImageView.contentMode = UIViewContentModeRedraw;
        //        [self generatePhotoThumbnail:[_selectedPhotos objectAtIndex:indexPath.row]];
        cell2.myImageView.image = [_selectedPhotos objectAtIndex:indexPath.row];
       
        
        
        if (indexP.row == indexPath.row) {
            
            if (_textStr != nil) {
                cell2.myLabel.text = _textStr;
                cell2.height = _fH;
            }

        }
        
        
      
        
        
     
        
     //   [cell2 addGestureRecognizer:ta];
        return cell2;
    }
    
    if (indexPath.section == 1) {
        
        //图片
        
        UITableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:@"ce" forIndexPath:indexPath];
        
        
        
        cell3.selectionStyle = UITableViewCellSelectionStyleNone;
        cell3.backgroundColor = LV;
        indexP = indexPath;
        
        
        
        
        //    裁掉view的边界
        self.myCollectionView.layer.masksToBounds = NO;
        //    设置半径
        //self.myCollectionView.layer.cornerRadius = 6 * AUTO_WIDTH;
        self.myCollectionView.scrollEnabled = NO;
        // self.myCollectionView.backgroundColor = [UIColor whiteColor];
        //  [self changeUICollectionView];
        [cell3 addSubview:_myCollectionView];
        
        
        _myCollectionView.contentInset = UIEdgeInsetsMake(13 * AUTO_WIDTH, 15 * AUTO_HEIGHT, 5 * AUTO_WIDTH, 15 * AUTO_HEIGHT);
        _myCollectionView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -2 * AUTO_HEIGHT);
        _myCollectionView.dataSource = self;
        _myCollectionView.delegate = self;
        
        
        //   [self changeUICollectionView];
        [_myCollectionView registerClass:[TZTestCell class] forCellWithReuseIdentifier:@"TZTestCell"];
        
        [_myCollectionView registerClass:[YHYPictureCollectionViewCell class] forCellWithReuseIdentifier:@"YHYPicCollectionViewCell"];
        //  UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(buttonLongPressed:)];
        //    [_myCollectionView addGestureRecognizer:longGesture];
        
        
        
        //        [cell3 addSubview:self.numLabel];
        //        self.numLabel.textColor = [UIColor blackColor];
        //        self.numLabel.alpha = 0.6;
        //        self.numLabel.font = [UIFont systemFontOfSize:TEXTLABELFONT*TEXTWEIGHT];
        //      //  [self changeUICollectionView];
        //
        //        [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.top.mas_equalTo(_myCollectionView.mas_bottom).offset(11 * AUTO_HEIGHT);
        //            make.left.mas_equalTo(cell3.mas_right).offset( - 50  * AUTO_WIDTH);
        //            make.height.mas_equalTo(15 * AUTO_WIDTH);
        //
        //
        //        }];
        //
        //        self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
        //        [_myCollectionView reloadData];
        
        return cell3;
        
        
        
        //    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
        
        
    }
    if (indexPath.section == 2) {
        YHYButtonTableViewCell *cellb = [tableView dequeueReusableCellWithIdentifier:@"YHYButtonTableViewCell"];
        cellb.delegate = self;
        cellb.selectionStyle = UITableViewCellSelectionStyleNone;
        [cellb.button setTitle:@"保存" forState:UIControlStateNormal];
        return cellb;
    }
    return nil;
    
}









- (void)goNext:(UIButton *)btu{
    [self.navigationController popViewControllerAnimated:YES];
}




//通知响应方法
- (void)change:(NSNotification *)notification
{
    NSMutableArray *ar = [notification object];
    self.selectedPhotos = ar;
    NSLog(@"qqqq%@",ar);
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    [_myCollectionView reloadData];
    
}

#pragma mark - 发布协议
- (void)presentDelegate{
    [self.navigationController popViewControllerAnimated:YES];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    //    NSLog(@"number:%ld", _selectedPhotos.count);
    //    if (_selectedPhotos.count >= 9) {
    //        return _selectedPhotos.count;
    //    }
    //    else{
    //        return _selectedPhotos.count + 1;
    //
    //    }
    return 1;
    
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    TZTestCell *cell1 =  [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    if (indexPath.row == _selectedPhotos.count && _selectedPhotos.count <= 9) {
        
        //        YHYPictureCollectionViewCell *cell1 = [collectionView   dequeueReusableCellWithReuseIdentifier:@"YHYPicCollectionViewCell" forIndexPath:indexPath];
        
        cell1.imageView.image = [UIImage imageNamed:@"jia"];
        return cell1;
    }
    //    else{
    //        TZTestCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"TZTestCell" forIndexPath:indexPath];
    //
    //        if (!_selectedPhotos.count == 0) {
    //            cell.imageView.image = _selectedPhotos[indexPath.row];
    //
    //            NSLog(@"-------%@", _selectedPhotos);
    //        }
    //
    //        //        cell.imageI = _selectedPhotos[indexPath.row];
    //
    //
    //        return cell;
    //
    //
    //
    //
    //    }
    
    
    return cell1;
    
    // [_myTableView reloadData];
    
    
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    //    if (indexPath.row == _selectedPhotos.count) {
    
    
    [self pickPhotoButtonClick:nil];
    
}

-(UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    
    return newImage;
}


#pragma mark Click Event

- (IBAction)pickPhotoButtonClick:(UIButton *)sender {
    NSInteger mum = 9;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]initWithMaxImagesCount:mum selectArr:_selectedPhotos delegate:self];
    imagePickerVc.selectCount = _selectedPhotos.count;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
    
    
    //  [self changeUICollectionView];
    [_myCollectionView reloadData];
    [_myTableView reloadData];
    
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets{
    [_selectedPhotos addObjectsFromArray:photos];
    //  NSLog(@"wwww%ld",(unsigned long)photos.count);
    //[self configCollectionView];
    
    _myCollectionView.contentSize = CGSizeMake(0, ((_selectedPhotos.count + 2) / 3 ) * (_margin + _itemWH));
    
    
    self.numLabel.text = [NSString stringWithFormat:@"%ld/9",(long)_selectedPhotos.count];
    //   [self changeUICollectionView];
    [_myTableView reloadData];
    [_myCollectionView reloadData];
    
    
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//
//
//    return CGSizeMake(_itemWH, _itemWH);
//
//}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 2.0 * AUTO_WIDTH, 0);
}





//
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//
////    if (indexPath.section == 0) {
//        YHYCompanyAddPictureCell *cell1 = (YHYCompanyAddPictureCell *)[_myTableView cellForRowAtIndexPath:indexPath];
//
//    [UIView animateWithDuration:0.2 animations:^{
//        cell1.deleteButton.backgroundColor = [UIColor redColor];
//
//    }];
//
//    [_myTableView reloadData];
//
//        }
//



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (_selectedPhotos.count != 0) {
            
            
            
            if (indexP.row == indexPath.row) {
                return  (580/3 + 150/3 + _fH* AUTO_HEIGHT - 10 * AUTO_HEIGHT) * AUTO_HEIGHT;
            }
            else{
                return (580/3 + 150/3) * AUTO_HEIGHT;
            }
         
        
    }
        
    }
    if (indexPath.section == 1) {
        
        //
        //        //        NSInteger b = _selectedPhotos.count;
        //        if (_selectedPhotos.count < 3 ) {
        //            a = 0;
        //
        //        }
        //        if (_selectedPhotos.count >= 3 && _selectedPhotos.count <= 5) {
        //
        //            a = 1;
        //        }
        //        if ( _selectedPhotos.count > 5 && _selectedPhotos.count <= 9) {
        //            a = 2;
        //        }
        return 150 * AUTO_HEIGHT  ;
    }
    //  [self changeUICollectionView];
    [_myCollectionView reloadData];
    
    
    // return 470 * AUTO_HEIGHT;
    
    if (indexPath.section == 2) {
        return 140 * AUTO_HEIGHT;
    }
    return 0;
}


//- (void)changeUICollectionView{
//
//    if (_selectedPhotos.count < 3 ) {
//        a = 0;
//
//    }
//    if (_selectedPhotos.count >= 3 && _selectedPhotos.count <= 5) {
//
//        a = 1;
//    }
//    if ( _selectedPhotos.count > 5 && _selectedPhotos.count <= 9) {
//        a = 2;
//    }
//
//
//    _myCollectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 150 * AUTO_HEIGHT  + (110 * AUTO_HEIGHT* (a))- 0 * AUTO_HEIGHT * (a));
//
//
//}


//- (void)shakeAnimationForView:(UIView *)view point:(CGPoint)point{
//    //获取到当前的View
//    CALayer *viewLayer = view.layer;
//    //获取当前View位置
//    CGPoint position = viewLayer.position;
//    CGPoint x = CGPointMake(position.x + 9, position.y);
//    CGPoint y = CGPointMake(position.x - 9, position.y);
//
//    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
//    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
//    [animation setFromValue:[NSValue valueWithCGPoint:x]];
//    [animation setToValue:[NSValue valueWithCGPoint:y]];
//    [animation setAutoreverses:YES];
//    [animation setDuration:0.06];
//    [animation setRepeatCount:3];
//    [viewLayer addAnimation:animation forKey:nil];
//    
//    
//    
//}


- (void)Back:(UIButton*)btu{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
